<template>
  <div class="order-list-container">
    <el-card class="page-container">
      <template #header>
        <div class="header">
          <span>我的酒店订单</span>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="error" class="error-container">
        <el-empty :description="errorMessage">
          <template #extra>
            <el-button type="primary" @click="initData">重试</el-button>
          </template>
        </el-empty>
      </div>
      
      <div v-else>
        <el-table v-if="tableData.length > 0" :data="tableData" stripe style="width: 100%">
          <el-table-column prop="id" label="订单ID"/>
          <el-table-column prop="userId" label="用户ID"/>
          <el-table-column prop="roomType" label="房型"/>
          <el-table-column prop="amount" label="金额"/>
          <el-table-column prop="paymentMethod" label="支付方式"/>
          <el-table-column label="创建时间">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="退房时间">
            <template #default="{ row }">
              <el-tooltip effect="dark" placement="top" v-if="row.checkoutTime || row.checkout_time">
                <template #content>{{ formatDate(row.checkoutTime || row.checkout_time) }}</template>
                <span>{{ formatDate(row.checkoutTime || row.checkout_time) }}</span>
              </el-tooltip>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="订单状态">
            <template #default="{ row }">
              <el-tag type="info" v-if="row.cancelTime">已取消</el-tag>
              <el-tag type="warning" v-else-if="!row.payTime">未支付</el-tag>
              <el-tag type="success" v-else-if="row.checkoutTime || row.checkout_time">已退房</el-tag>
              <el-tag type="primary" v-else>已支付</el-tag>
            </template>
          </el-table-column>
        </el-table>
        
        <el-empty v-else description="暂无订单数据"></el-empty>
        
        <div v-if="tableData.length > 0" class="pagination-box">
          <el-pagination background layout="total, prev, pager, next"
                         v-model:current-page="pageIndex"
                         :page-size="pageSize"
                         @current-change="handleCurrentChange"
                         :total="total"/>
        </div>
      </div>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getOrderList } from '@/api/order'
import { ElMessage } from 'element-plus'
import { getHotelByUserId } from '@/api/hotel'
import { useUserInfoStore } from '@/stores/userInfo'

const tableData = ref([])
const loading = ref(true)
const error = ref(false)
const errorMessage = ref('获取订单列表失败')
const userInfoStore = useUserInfoStore()
const hotelName = ref('')
const pageIndex = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 格式化日期
const formatDate = (dateStr: string | null) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString()
}

const initData = async () => {
  if (!userInfoStore.userInfo || !userInfoStore.isHotelOwner()) {
    errorMessage.value = '您没有访问此页面的权限'
    error.value = true
    loading.value = false
    return
  }
  
  loading.value = true
  error.value = false
  
  try {
    // 先获取用户关联的酒店
    const userId = userInfoStore.userInfo.user.userId
    const hotelRes = await getHotelByUserId(userId)
    const hotelResult = hotelRes.data
    
    if (hotelResult && hotelResult.code === 200 && hotelResult.data) {
      hotelName.value = hotelResult.data.hotelName
      
      // 获取所有订单
      const res = await getOrderList()
      const result = res.data
      
      if (result && result.code === 200) {
        // 筛选当前酒店的订单
        const allOrders = Array.isArray(result.data) ? result.data : []
        tableData.value = allOrders.filter(order => order.hotelName === hotelName.value)
        total.value = tableData.value.length
        
        // 处理字段名称差异
        tableData.value = tableData.value.map(item => {
          // 确保数据一致性，处理可能的checkoutTime/checkout_time命名差异
          if (item && item.checkout_time && !item.checkoutTime) {
            item.checkoutTime = item.checkout_time
          }
          return item
        })
      } else {
        error.value = true
        errorMessage.value = result?.msg || '获取订单列表失败'
      }
    } else {
      error.value = true
      errorMessage.value = hotelResult?.msg || '获取酒店信息失败'
    }
  } catch (err) {
    console.error('获取订单列表错误:', err)
    error.value = true
    errorMessage.value = '网络错误，获取订单列表失败'
  } finally {
    loading.value = false
  }
}

const handleCurrentChange = (index: number) => {
  pageIndex.value = index
  // 这里我们在前端进行分页，因为已经筛选了当前酒店的订单
  // 实际项目中应该由后端提供酒店订单筛选API
}

onMounted(() => {
  initData()
})
</script>
<style scoped>
.order-list-container {
  padding: 20px;
}

.page-container {
  min-height: 600px;
}
.header { 
  display: flex; 
  justify-content: space-between; 
  align-items: center; 
}
.loading-container, .error-container {
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.pagination-box { 
  padding-top: 16px; 
  display: flex; 
  justify-content: right; 
}
</style> 